package com.nullpointer.xchat.fragment;

import java.util.Calendar;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.fourmob.datetimepicker.date.DatePickerDialog.OnDateSetListener;
import com.nullpointer.xchat.ProcessImage;
import com.nullpointer.xchat.R;
import com.nullpointer.xchat.fragment.ChooseImageDialogFragment.OnChooseImageDialogFragment;
import com.nullpointer.xchat.object.RoomType;
import com.nullpointer.xchat.object.UserInfo.GenderType;
import com.nullpointer.xchat.service.ChatService;
import com.nullpointer.xchat.utils.Common;
import com.nullpointer.xchat.utils.DataManager;
import com.nullpointer.xchat.utils.Utils;

public class EditProfileDialogFragment extends DialogFragment implements
		OnDateSetListener {
	private EditText etName;
	private ImageButton ibEditName;
	private EditText etStatus;
	private ImageButton ibEditStatus;
	private Button btAction;
	private boolean isChanged = false;
	private TextView tvMale;
	private TextView tvFemale;
	private TextView tvOther;
	private GenderType gender;
	private int focus = Color.parseColor("#ff8800");
	private int normal = Color.parseColor("#333333");
	private DatePickerDialog datePickerDialog;
	private TextView tvBirthday;
	private ImageButton ibEditBirthday;
	public static final String DATEPICKER_TAG = "datepicker";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_profile, container);
		findViewIds(view);
		init();
		setEvent();
		return view;
	}

	private void init() {
		getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
		tvBirthday.setText(DataManager.getInstance(getActivity())
				.getUserBirthday());
		etName.setText(DataManager.getInstance(getActivity()).getUserName());
		etStatus.setText(DataManager.getInstance(getActivity()).getUserStatus());
		gender = DataManager.getInstance(getActivity()).getUserGender();
		if (gender == GenderType.FEMALE) {
			tvFemale.setTextColor(focus);
			tvMale.setTextColor(normal);
			tvOther.setTextColor(normal);
		} else if (gender == GenderType.MALE) {
			tvFemale.setTextColor(normal);
			tvMale.setTextColor(focus);
			tvOther.setTextColor(normal);
		} else if (gender == GenderType.ANY) {
			tvFemale.setTextColor(normal);
			tvMale.setTextColor(normal);
			tvOther.setTextColor(focus);
		}
		etName.setEnabled(false);
		etStatus.setEnabled(false);
	}

	private void setEvent() {
		btAction.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Utils.hideKeyboard(getActivity(), etStatus);
				Utils.hideKeyboard(getActivity(), etName);
				if (isChanged) {
					updateProfile();
				} else {
					dismiss();
				}

			}
		});

		ibEditName.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				etName.setEnabled(true);
				etName.requestFocus();
				setUpdateButton();
			}
		});

		ibEditStatus.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				etStatus.setEnabled(true);
				etStatus.requestFocus();
				setUpdateButton();
			}
		});

		ibEditBirthday.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String[] dateString = convertStringToDate(DataManager
						.getInstance(getActivity()).getUserBirthday());
				int year = Integer.parseInt(dateString[0]);
				int month = Integer.parseInt(dateString[1]);
				int day = Integer.parseInt(dateString[2]);
				datePickerDialog = DatePickerDialog.newInstance(
						EditProfileDialogFragment.this, year, month, day, true);
				datePickerDialog.setYearRange(1902, 2000);
				datePickerDialog.setCloseOnSingleTapDay(true);
				FragmentTransaction transaction = getActivity()
						.getSupportFragmentManager().beginTransaction();
				transaction.add(datePickerDialog, DATEPICKER_TAG);
				transaction.commitAllowingStateLoss();
				setUpdateButton();
			}
		});

		etName.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (etName.getText() != null
						&& etName.getText().toString().trim().length() >= 3) {
					if (Utils.checkBadword(etName.getText().toString())) {
						btAction.setText("Don't use sexual content!");
						btAction.setEnabled(false);
					} else {
						btAction.setText("Save");
						btAction.setEnabled(true);
					}
				} else {
					btAction.setText("Name must > 3 char");
					btAction.setEnabled(false);
				}
			}
		});

		etStatus.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

				if (Utils.checkBadword(etStatus.getText().toString())) {
					btAction.setText("Don't use sexual content!");
					btAction.setEnabled(false);
				} else {
					btAction.setText("Save");
					btAction.setEnabled(true);
				}

			}
		});

		tvFemale.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (gender != GenderType.FEMALE) {
					tvFemale.setTextColor(focus);
					tvMale.setTextColor(normal);
					tvOther.setTextColor(normal);
					gender = GenderType.FEMALE;
					setUpdateButton();
				}

			}
		});
		tvMale.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (gender != GenderType.MALE) {
					tvFemale.setTextColor(normal);
					tvMale.setTextColor(focus);
					tvOther.setTextColor(normal);
					gender = GenderType.MALE;
					setUpdateButton();
				}
			}
		});
		tvOther.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (gender != GenderType.ANY) {
					tvFemale.setTextColor(normal);
					tvMale.setTextColor(normal);
					tvOther.setTextColor(focus);
					gender = GenderType.ANY;
					setUpdateButton();
				}
			}
		});
	}

	protected void updateProfile() {
		String name = etName.getText().toString();
		String status = etStatus.getText().toString();
		if (!name.equals(DataManager.getInstance(getActivity()).getUserName())
				|| !status.equals(DataManager.getInstance(getActivity())
						.getUserStatus())
				|| gender != DataManager.getInstance(getActivity())
						.getUserGender()) {
			DataManager.getInstance(getActivity()).setUserName(name);
			DataManager.getInstance(getActivity()).setUserStatus(status);
			DataManager.getInstance(getActivity()).setUserGender(gender);
			boolean isInvisible = DataManager.getInstance(getActivity())
					.getInvisibleSetting();
			RoomType room = DataManager.getInstance(getActivity())
					.getCurrentRoom();
			ChatService.getInstance().updateProfile(true, isInvisible, room);
		}
		dismiss();
	}

	protected void setUpdateButton() {
		isChanged = true;
		btAction.setText("Save");
	}

	private void findViewIds(View view) {
		etName = (EditText) view.findViewById(R.id.et_name);
		ibEditName = (ImageButton) view.findViewById(R.id.ib_edit_name);
		etStatus = (EditText) view.findViewById(R.id.et_status);
		ibEditStatus = (ImageButton) view.findViewById(R.id.ib_edit_status);
		btAction = (Button) view.findViewById(R.id.bt_action);
		tvMale = (TextView) view.findViewById(R.id.tv_male);
		tvFemale = (TextView) view.findViewById(R.id.tv_female);
		tvOther = (TextView) view.findViewById(R.id.tv_other);
		tvBirthday = (TextView) view.findViewById(R.id.tv_birthday);
		ibEditBirthday = (ImageButton) view.findViewById(R.id.ib_edit_birthday);
	}

	@Override
	public void onDismiss(DialogInterface dialog) {
		super.onDismiss(dialog);
		Utils.hideKeyboard(getActivity(), etStatus);
		Utils.hideKeyboard(getActivity(), etName);
	}

	@Override
	public void onCancel(DialogInterface dialog) {
		super.onCancel(dialog);
		Utils.hideKeyboard(getActivity(), etStatus);
		Utils.hideKeyboard(getActivity(), etName);
	}

	protected void showChooseImageFragment() {
		final ChooseImageDialogFragment dialog = new ChooseImageDialogFragment();
		dialog.setOnChooseImageDialogFragment(new OnChooseImageDialogFragment() {

			@Override
			public void onGallery() {
				selectImageFromGallery();
			}

			@Override
			public void onCamera() {
				selectImageFromCamera();
			}
		});
		FragmentTransaction transaction = getActivity()
				.getSupportFragmentManager().beginTransaction();
		transaction.add(dialog, "ChooseImageDialogFragmentEditProfile");
		transaction.commitAllowingStateLoss();
	}

	protected void selectImageFromGallery() {
		Intent intent = new Intent(getActivity(), ProcessImage.class);
		intent.putExtra(ProcessImage.IS_SELECT_IMAGE_FROM_CAMERA, false);
		intent.putExtra(ProcessImage.ASPECT_RATIO_X, 100);
		intent.putExtra(ProcessImage.ASPECT_RATIO_Y, 100);
		startActivityForResult(intent, Common.RequestCode.EDIT_AVATAR_PROFILE);
	}

	protected void selectImageFromCamera() {
		Intent intent = new Intent(getActivity(), ProcessImage.class);
		intent.putExtra(ProcessImage.IS_SELECT_IMAGE_FROM_CAMERA, true);
		intent.putExtra(ProcessImage.ASPECT_RATIO_X, 100);
		intent.putExtra(ProcessImage.ASPECT_RATIO_Y, 100);
		startActivityForResult(intent, Common.RequestCode.EDIT_AVATAR_PROFILE);
	}

	@Override
	public void onDateSet(DatePickerDialog datePickerDialog, int year,
			int month, int day) {
		DataManager.getInstance(getActivity()).setUserBirthday(
				convertDateToString(year, month, day));
		tvBirthday.setText(convertDateToString(year, month, day));
	}

	private String[] convertStringToDate(String date) {
		return date.split("/");
	}

	private String convertDateToString(int year, int month, int day) {
		return year + "/" + ((month < 10) ? "0" + month : month) + "/"
				+ ((day < 10) ? "0" + day : day);
	}
}
